﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MPExtractor.Classes;
using System.Collections.ObjectModel;
using Microsoft.Win32;
using Microsoft.EnterpriseManagement.Configuration.IO;
using Microsoft.EnterpriseManagement.Packaging;
using System.IO;
using Microsoft.EnterpriseManagement.Configuration;
using System.Reflection;


namespace MPExtractor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        MonitoringPacks MP = new MonitoringPacks();
        public ObservableCollection<MonitoringPacks> MPS = new ObservableCollection<MonitoringPacks>();

        public MainWindow()
        {
            InitializeComponent();
            ListFiles.ItemsSource = MPS;

            extractpath.Text = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        }

        private void Window_Drop(object sender, DragEventArgs e)
        {
            
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] file = (string[])e.Data.GetData(DataFormats.FileDrop);
                foreach(string f in file)
                {
                    MPS.Add(new MonitoringPacks { Path = f });
                }
                
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            foreach(MonitoringPacks m in MPS)
            {
                
                if(System.IO.Path.GetExtension(m.Path) == ".mp")
                {
                    MP.ExtractMP(m.Path, extractpath.Text);
                }
                else if (System.IO.Path.GetExtension(m.Path) == ".mpb")
                {
                   // MP.ExtractMPB(m.Path, extractpath.Text);

                    string outpath = extractpath.Text;


                    String[] path = new String[] { m.Path };
                    ManagementPackFileStore mpStore = new ManagementPackFileStore(path);

                    ManagementPackBundleReader mpbReader = ManagementPackBundleFactory.CreateBundleReader();

                    

                    ManagementPackBundle mpb = mpbReader.Read(m.Path, mpStore);

                    //mpWrite.WriteManagementPack(mpb.ManagementPacks[0]);
                    
                    //IDictionary<string, Stream> stream = mpb.GetStreams(mpb.ManagementPacks[0]);

                    foreach(ManagementPack mp in mpb.ManagementPacks)
                    {

                        Directory.CreateDirectory(outpath + @"\" + mp.Name);
                        ManagementPackXmlWriter mpWrite = new ManagementPackXmlWriter(outpath + @"\" + mp.Name);
                        mpWrite.WriteManagementPack(mp);
                        IDictionary<string, Stream> streams = mpb.GetStreams(mp);

                        foreach (string stream in streams.Keys)
                        {
                            System.Type t = mp.FindManagementPackElementByName(stream).GetType();
                           // MessageBox.Show(t.Name);


                            // ManagementPackDeployableResource
                            // ManagementPackDeployableAssemblyResource
                            // ManagementPackImage
                            // ManagementPackAssemblyResource
                            
                           
                            dynamic mpElement;
                            if (t.Name == "ManagementPackDeployableResource")
                            {
                                mpElement = (ManagementPackDeployableResource)mp.FindManagementPackElementByName(stream);

                            }
                            else if (t.Name == "ManagementPackDeployableAssemblyResource")
                            {
                                mpElement = (ManagementPackDeployableAssemblyResource)mp.FindManagementPackElementByName(stream);
                            }
                            else if (t.Name == "ManagementPackAssemblyResource")
                            {
                                mpElement = (ManagementPackAssemblyResource)mp.FindManagementPackElementByName(stream);
                            }
                            else
                            {
                                mpElement = (ManagementPackImage)mp.FindManagementPackElementByName(stream);
                            }
                                // mpElment = (ManagementPackDeployableResource)mp.FindManagementPackElementByName(stream);

                                //ManagementPackDeployableResource mpElement = (ManagementPackDeployableResource)mp.FindManagementPackElementByName(stream);

                                string filename = mpElement.FileName;
                                //MessageBox.Show(filename);
                                if (filename == null)
                                {
                                    filename = outpath + @"\" + mp.Name + "." + stream + ".bin";
                                    MessageBox.Show(filename);

                                }
                                else
                                {
                                   
                                    if (filename.IndexOf(@"\") > 0)
                                    {
                                        MessageBox.Show(filename.IndexOf(@"\").ToString());
                                        string dir = outpath + @"\" + filename.Substring(0, filename.IndexOf(@"\"));
                                        Directory.CreateDirectory(dir);
                                        MessageBox.Show(dir);

                                    }
                                    filename = outpath + @"\" + mp.Name + @"\" + filename;

                                }
                               var q = File.Create(filename);
                               streams[stream].CopyTo(q);
                               q.Close();
                                
                                //MessageBox.Show(filename);
                            }

                        

                    }


                }
                
            }

        }



        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            var result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                extractpath.Text = dialog.SelectedPath;
            }

        }

        private void Remove_Click(object sender, RoutedEventArgs e)
        {

            while (ListFiles.SelectedItems.Count > 0)
            {
                MPS.Remove((MonitoringPacks)ListFiles.SelectedItem);
            }

        }
    }
}
